package com.mate.cloud.codegen.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.creator.druid.DruidConfig;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mate.cloud.codegen.domain.GenDatasourceConf;
import com.mate.cloud.codegen.mapper.GenDatasourceConfMapper;
import com.mate.cloud.codegen.service.GenDatasourceConfService;
import com.mate.cloud.codegen.util.SpringContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据源表
 * https://www.cnblogs.com/starsray/p/15557151.html
 * @author: MI
 * @email: 448341911@qq.com
 * @createDate: 2023/11/5 21:15
 * @updateUser: MI
 * @updateDate: 2023/11/5 21:15
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfMapper, GenDatasourceConf> implements GenDatasourceConfService {


    private final DefaultDataSourceCreator druidDataSourceCreator;

    private final StringEncryptor stringEncryptor;


    /**
     * 保存数据源并且加密
     *
     * @param conf
     * @return
     */
    @Override
    public Boolean saveDsByEnc(GenDatasourceConf conf) {
        if (!checkDataSource(conf)) {
            return Boolean.FALSE;
        }
        // 添加动态数据源
        addDynamicDataSource(conf);

        // 更新动态数据源
        conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
        this.baseMapper.insert(conf);
        return Boolean.TRUE;
    }

    /**
     * 更新数据源
     *
     * @param conf 数据源信息
     * @return
     */
    @Override
    public Boolean updateDsByEnc(GenDatasourceConf conf) {
        if (!checkDataSource(conf)) {
            return Boolean.FALSE;
        }

        // 先移除
        DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
        dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(conf.getId()).getName());

        // 再添加
        addDynamicDataSource(conf);

        // 更新数据库配置
        if (StringUtils.isNotEmpty(conf.getPassword())) {
            conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
        }
        this.baseMapper.updateById(conf);
        return Boolean.TRUE;
    }

    /**
     * 添加动态数据源
     *
     * @param conf 数据源信息
     */
    @Override
    public void addDynamicDataSource(GenDatasourceConf conf) {
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setPoolName(conf.getName());
        dataSourceProperty.setUrl(conf.getUrl());
        dataSourceProperty.setUsername(conf.getUsername());
        dataSourceProperty.setPassword(conf.getPassword());
        // 增加 ValidationQuery 参数
        DruidConfig druidConfig = new DruidConfig();
        dataSourceProperty.setDruid(druidConfig);

        DataSource dataSource = druidDataSourceCreator.createDataSource(dataSourceProperty);
        DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
        dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
    }

    /**
     * 校验数据源配置是否有效
     *
     * @param conf 数据源信息
     * @return 有效/无效
     */
    @Override
    public Boolean checkDataSource(GenDatasourceConf conf) {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(conf.getUrl(), conf.getUsername(), conf.getPassword());
        } catch (SQLException e) {
            log.error("数据源配置 {} , 获取链接失败", conf.getName(), e);
            return Boolean.FALSE;
        } finally {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 通过数据源名称删除
     *
     * @param dsId 数据源ID
     * @return
     */
    @Override
    public Boolean removeByDsId(Integer dsId) {

        DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
        this.baseMapper.selectBatchIds(CollUtil.toList(dsId))
                .forEach(ds -> dynamicRoutingDataSource.removeDataSource(ds.getName()));
        this.baseMapper.deleteBatchIds(CollUtil.toList(dsId));
        return Boolean.TRUE;
    }
}
